from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re
from apps.users.models import User
from utils.secret import SecretOauth



def generate_verify_email_url(user):
    # 1.userid email
    data_dict = {'user_id': user.id, 'email': user.email}
    # 2. 加密
    secret_data = SecretOauth().dumps(data_dict)
    # 3. 拼接 链接
    verify_url = settings.EMAIL_ACTIVE_URL + '?token=' + secret_data
    # 4.返回去
    return verify_url


# 自定义认证后端方法
class UsernameMobileAuthBackend(ModelBackend):
    # 重写父类方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 3.1 如果是手机号  验证码手机号
        if re.match('^1[345789]\d{9}$', username):
            user = User.objects.get(mobile=username)
        # 3.2 不是手机号  ,验证username
        else:
            user = User.objects.get(username=username)

        if user and user.check_password(password):
            return user
